<template>
  <div class="login">
    <van-nav-bar
      title="用户登录"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    />
    <van-form @submit="login">
      <van-field
        v-model="loginForm.mobile"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[
        { required: true, message: '请填写手机号',trigger:'onBlur'},
        { pattern:/^1[3-9]\d{9}$/, message: '请输入正确的11位手机号码',trigger:'onChange'}
        ]"
      />
      <van-field
        v-model="loginForm.code"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[
        { required: true, message: '请输入验证码',trigger:'onBlur'},
        { pattern:/^\d{6}$/, message: '请输入6位验证码',trigger:'onChange' }
        ]"
      />
      <div class="btn-wrap" style="margin: 16px;">
        <van-button  block type="primary" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
export default {
  data () {
    return {
      loginForm: {
        mobile: '13912345678',
        code: '246810'
      }

    }
  },
  methods: {
    async login () {
      this.$toast.loading({
        durations: 0, // 持续展示toast，永远不会关闭
        overlay: true, // 整体加个遮罩
        message: '加载中',
        forbidClick: true
      })
      try {
        console.log(this.$route)
        await this.$store.dispatch('user/login', this.loginForm)
        const backto = this.$route.query.backto || '/'
        this.$router.push(backto)
        // this.$router.push('/')
        this.$toast.success('success')
      } catch (error) {
        console.log(error)
        // 一个页面上只能有一个toast，它会把上面的loading状态覆盖掉
        this.$toast.fail('验证码错误')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login {
  .btn-wrap {
    padding: 20px;
    .van-button {
      width: 100%;
      color: #fff;
      border-radius: 5px;
    }
  }
}
</style>
